/**
 * API 实例封装
 */

import ky, { type KyInstance, type Options } from 'ky'
import { tokenManager } from '@/utils/token'
import { API_CONFIG, HTTP_STATUS, BUSINESS_CODE } from './config'
import type { ApiResponse, RequestOptions } from '@/types/api'

/** 创建 Ky 实例 */
const createKyInstance = (): KyInstance => {
  return ky.create({
    prefixUrl: API_CONFIG.BASE_URL,
    timeout: API_CONFIG.TIMEOUT,
    retry: API_CONFIG.RETRY_COUNT,
    // 不设置默认headers，避免文件上传时Content-Type冲突
    hooks: {
      beforeRequest: [
        async (request) => {
          // 自动添加 token
          // const token = await tokenManager.getToken()
          const token = 'N2I2YTUzZTYtYzliZi00MDEzLWEzNDMtMDA5ZjA2ZjdiYjc4'
          if (token) {
            request.headers.set('Authorization', `Bearer ${token}`)
          }

          console.log(`🚀 API请求: ${request.method} ${request.url}`)
          // console.log('token:', token)
        },
      ],
      beforeRetry: [
        ({ request, options, error, retryCount }) => {
          console.warn(
            `🔄 重试请求 (${retryCount}/${options.retry}): ${request.method} ${request.url}`,
            error,
          )
        },
      ],
      afterResponse: [
        async (request, options, response) => {
          console.log(`✅ API响应: ${request.method} ${request.url} - ${response.status}`)

          // 处理 401 未授权
          if (response.status === HTTP_STATUS.UNAUTHORIZED) {
            console.warn('Token已过期，清除本地token')
            tokenManager.clearToken()
            // 可以在这里触发重新获取token的逻辑
          }

          return response
        },
      ],
      beforeError: [
        (error) => {
          const { request, response } = error
          console.error(`❌ API错误: ${request.method} ${request.url}`, {
            status: response?.status,
            statusText: response?.statusText,
            error,
          })
          return error
        },
      ],
    },
  })
}

// 创建实例
const apiInstance = createKyInstance()

/** 通用请求方法 */
class ApiClient {
  private instance: KyInstance

  constructor(instance: KyInstance) {
    this.instance = instance
  }

  /** GET 请求 */
  async get<T = any>(url: string, options?: Options & RequestOptions): Promise<ApiResponse<T>> {
    return this.request<T>(url, { ...options, method: 'GET' })
  }

  /** POST 请求 */
  async post<T = any>(
    url: string,
    data?: any,
    options?: Options & RequestOptions,
  ): Promise<ApiResponse<T>> {
    return this.request<T>(url, {
      ...options,
      method: 'POST',
      json: data,
    })
  }

  /** PUT 请求 */
  async put<T = any>(
    url: string,
    data?: any,
    options?: Options & RequestOptions,
  ): Promise<ApiResponse<T>> {
    return this.request<T>(url, {
      ...options,
      method: 'PUT',
      json: data,
    })
  }

  /** DELETE 请求 */
  async delete<T = any>(url: string, options?: Options & RequestOptions): Promise<ApiResponse<T>> {
    return this.request<T>(url, { ...options, method: 'DELETE' })
  }

  /** 通用请求方法 */
  private async request<T>(
    url: string,
    options: Options & RequestOptions = {},
  ): Promise<ApiResponse<T>> {
    const {
      loading = false,
      showError = true,
      errorHandler,
      timeout,
      retry,
      ...kyOptions
    } = options

    // 合并配置
    const requestOptions: Options = {
      ...kyOptions,
      ...(timeout && { timeout }),
      ...(retry !== undefined && { retry }),
       // 如果不是文件上传，则添加默认headers
      ...(kyOptions.body instanceof FormData ? {} : { headers: API_CONFIG.HEADERS }),
    }

    try {
      // 显示加载状态（如果需要）
      if (loading) {
        // 这里可以集成全局loading状态管理
        console.log('🔄 显示加载状态')
      }

      const response = await this.instance(url, requestOptions)
      const result = await response.json<ApiResponse<T>>()
      console.log('result:', result)

      // 检查业务状态码 - 允许200和201都作为成功状态
      if (result.code !== BUSINESS_CODE.SUCCESS && result.code !== 200) {
        throw new Error(result.message || '请求失败')
      }

      return result
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '网络请求失败'

      console.error('🚨 请求错误详情:', {
        error,
        message: errorMessage,
        url,
        options: requestOptions
      })

      // 自定义错误处理
      if (errorHandler) {
        errorHandler(error as Error)
      } else if (showError) {
        // 这里可以集成全局错误提示
        console.error('🚨 请求错误:', errorMessage)
      }

      throw error
    } finally {
      // 隐藏加载状态
      if (loading) {
        console.log('✅ 隐藏加载状态')
      }
    }
  }

  /** 上传文件 */
  async upload<T = any>(
    url: string,
     formData: FormData,
    options?: Options & RequestOptions,
  ): Promise<ApiResponse<T>> {
    

    return this.request<T>(url, {
      ...options,
      method: 'POST',
      body: formData,
      // 文件上传时不设置Content-Type，让浏览器自动设置multipart/form-data
    })
  }
}

// 导出API客户端实例
export const apiClient = new ApiClient(apiInstance)
export { apiInstance }
